﻿//函数语法糖
(function () {
    if (typeof Function.prototype.method !== "function") {
        Function.prototype.method = function (name, implementation) {
            this.prototype[name] = implementation;
            return this;
        };
    }

    var Person = function (name) {
        this.name = name;
    }
    .method('getName', function () {
        return this.name;
    })
    .method('setName', function (name) {
        this.name = name;
        return this;
    });

    var a = new Person('admin');
    console.log(a.getName());
    console.log(a.setName('Eve').getName());
}());

//对象常量
var constant = (function () {
    var constants = {},
          ownProp = Object.prototype.hasOwnProperty,
          allowed = {
              string: 1,
              number: 1,
              boolean: 1
          },
          prefix = (Math.random() + "_").slice(2);

    return {
        set: function (name, value) {
            if (this.isDefined(name)) {
                return false;
            }
            if (!ownProp.call(allowed, typeof value)) {
                return false;
            }
            constants[prefix + name] = value;
            return true;
        },
        isDefined: function (name) {
            return ownProp.call(constants, prefix + name);
        },
        get: function (name) {
            if (this.isDefined(name)) {
                return constants[prefix + name];
            }
            return null;
        }
    };
}());

console.log(constant.isDefined('maxwidth'));
console.log(constant.set('maxwidth', 480));
console.log(constant.isDefined("maxwidth"));
console.log(constant.set("maxwidth", 320));
console.log(constant.get("maxwidth"));

//静态成员
(function () {
    var Gadget = function () { };

    Gadget.isShiny = function () {
        return "you bet";
    };

    Gadget.prototype.setPrice = function (price) {
        this.price = price;
    };

    console.log(Gadget.isShiny());
    var iphone = new Gadget();
    iphone.setPrice(500);
    console.log(typeof Gadget.setPrice);
    console.log(typeof iphone.isShiny);
    Gadget.prototype.isShiny = Gadget.isShiny;
    console.log(iphone.isShiny());
}());

var Gadget = (function () {
    var counter = 0;

    return function () {
        console.log(counter += 1);
    };
}());

var g1 = new Gadget(); // logs 1
var g2 = new Gadget(); // logs 2
var g3 = new Gadget(); // logs 3

var Gadget = (function () {
    var counter = 0,
          NewGadget;

    NewGadget = function () {
        counter += 1;
    };
    NewGadget.prototype.getLastId = function () {
        return counter;
    };
    return NewGadget;
}());

var iphone = new Gadget();
iphone.getLastId(); // 1
var ipod = new Gadget();
ipod.getLastId(); // 2
var ipad = new Gadget();
ipad.getLastId(); // 3
